// 从数组中 随机返回一个数字
function getNum(list) {
  list.sort(() => Math.random() - 0.5).sort(() => Math.random() - 0.5);
  let r = list.pop();
  return r;
}

// 随机生成指定个随机数字 几取几
function getNumList(sourceNum, num, excludes) {
  return new Promise(async (resolve, reject) => {
    let source = [];
    let result = [];
    for (let i = 1; i <= sourceNum; i++) {
      if (!excludes.includes(i)) {
        source.push(i);
      }
    }

    await createNum(20, source, result, num);
    result.sort((a, b) => a - b);
    // console.log('随机数字组：', result);
    resolve(result);
  });
}

// 从指定数字中获取N个随机数
function createNum(time, source, result, num) {
  return new Promise((resolve, reject) => {
    setTimeout(async () => {
      result.push(getNum(source));
      if (result.length < num) {
        let time = parseInt(Math.random() * 500);
        await createNum(time, source, result, num);
      }
      resolve(result);
    }, time);
  });

  // setTimeout(() => {
  //   result.push(getNum(source));
  //   if (result.length < num) {
  //     let time = parseInt(Math.random() * 500);
  //     createNum(time, source, result, num);
  //   }
  // },time );
}

// 生成不通类型的随机数组
async function createBallList(type, blueExcludes = [], redExcludes = []) {
  let double = {
    red: {
      sourceNum: 33,
      num: 6,
      excludes: [],
    },
    blue: {
      sourceNum: 16,
      num: 1,
      excludes: [],
    },
  };

  let ballInfo = {};
  // console.log('⌛️生成中...')
  ballInfo["red"] = await getNumList(double.red.sourceNum, double.red.num, [
    ...redExcludes,
    ...double.red.excludes,
  ]);
  ballInfo["blue"] = await getNumList(double.blue.sourceNum, double.blue.num, [
    ...blueExcludes,
    ...double.blue.excludes,
  ]);
  // console.log('✅生成完成')
  return ballInfo;
}

// num: 获取几组数据
function getBallList(
  num,
  result = [],
  callback = () => {},
  blueExcludes = [],
  redExcludes = [],
  isExcludeBlue = true
) {
  let exitBlue = [];
  if (isExcludeBlue) {
    exitBlue = result.reduce((pre, cur) => {
      return [...pre, ...cur.blue];
    }, []);
  }

  blueExcludes = [...blueExcludes, ...exitBlue];

  createBallList("1", blueExcludes, redExcludes).then((res) => {
    console.log(`生成中...`);
    callback(result);
    if (result.length < num) {
      getBallList(
        num,
        result.concat(res),
        callback,
        blueExcludes,
        redExcludes,
        true
      );
    } else {
      console.log(`${num}组生成完成！`, result);
    }
  });
}
